package com.iot08.api.service;

import com.iot08.common.entity.app.MessageStats;
import com.iot08.common.service.base.BaseService;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.Date;

@Service
public class MessageStatsService extends BaseService<MessageStats> {
    private static final int ROLLING_DAYS = 31;

    /**
     * 更新消息统计
     */
    public void updateSuccess(String id) {
        updateSuccessStats(id, 1);
    }

    /**
     * 更新错误消息统计 
     */
    public void updateError(String id) {
        updateErrorStats(id, 1);
    }
//
//    // 核心私有方法
//    private void updateStats(String id, String dailyField, String totalField, int count) {
//        String today = LocalDate.now().toString();
//        String oldestDay = LocalDate.now().minusDays(ROLLING_DAYS).toString();
//
//        // 先查询旧数据，看是否需要减去
//        MessageStats existingStats = findById(id);
//        int oldCount = 0;
//        if (existingStats != null) {
//            if (dailyField.equals("successDaily") && existingStats.getSuccessDaily() != null) {
//                oldCount = existingStats.getSuccessDaily().getOrDefault(oldestDay, 0);
//            } else if (dailyField.equals("errorDaily") && existingStats.getErrorDaily() != null) {
//                oldCount = existingStats.getErrorDaily().getOrDefault(oldestDay, 0);
//            }
//        }
//
//        Update update = new Update()
//            .inc(dailyField + "." + today, count)
//            .inc(totalField, count - oldCount)
//            .set("last_updated", new Date())
//            .setOnInsert("_id", id);
//        //  .unset(dailyField + "." + oldestDay)
////            .setOnInsert(dailyField + "." + today, count)
////            .setOnInsert(totalField, count);
//        if (oldCount > 0 && !today.equals(oldestDay)) {
//            update.unset(dailyField + "." + oldestDay);
//        }
//        mongoTemplate.upsert(
//            Query.query(Criteria.where("_id").is(id)),
//            update,
//            MessageStats.class
//        );
//    }
// 更新成功统计
private void updateSuccessStats(String id, int count) {
    String today = LocalDate.now().toString();
    String oldestDay = LocalDate.now().minusDays(ROLLING_DAYS).toString();

    // 获取旧数据
    MessageStats existingStats = findById(id);
    int oldSuccessCount = 0;
    if (existingStats != null && existingStats.getSuccessDaily() != null) {
        oldSuccessCount = existingStats.getSuccessDaily().getOrDefault(oldestDay, 0);
    }

    Update update = new Update()
            .inc("successDaily." + today, count)
            .inc("successTotal", count - oldSuccessCount)
            .set("last_updated", new Date())
            .setOnInsert("_id", id);

    if (oldSuccessCount > 0 && !today.equals(oldestDay)) {
        update.unset("successDaily." + oldestDay);
    }

    mongoTemplate.upsert(
            Query.query(Criteria.where("_id").is(id)),
            update,
            MessageStats.class
    );
}

    // 更新错误统计
    private void updateErrorStats(String id, int count) {
        String today = LocalDate.now().toString();
        String oldestDay = LocalDate.now().minusDays(ROLLING_DAYS).toString();

        // 获取旧数据
        MessageStats existingStats = findById(id);
        int oldErrorCount = 0;
        if (existingStats != null && existingStats.getErrorDaily() != null) {
            oldErrorCount = existingStats.getErrorDaily().getOrDefault(oldestDay, 0);
        }

        Update update = new Update()
                .inc("errorDaily." + today, count)
                .inc("errorTotal", count - oldErrorCount)
                .set("last_updated", new Date())
                .setOnInsert("_id", id);

        if (oldErrorCount > 0 && !today.equals(oldestDay)) {
            update.unset("errorDaily." + oldestDay);
        }

        mongoTemplate.upsert(
                Query.query(Criteria.where("_id").is(id)),
                update,
                MessageStats.class
        );
    }
    /**
     * 获取成功消息总数
     */
    public int getSuccessTotal(String id) {
        MessageStats stats = findById(id);
        return stats != null && stats.getSuccessTotal() != null ? 
               stats.getSuccessTotal() : 0;
    }

    /**
     * 获取错误消息总数
     */
    public int getErrorTotal(String id) {
        MessageStats stats = findById(id);
        return stats != null && stats.getErrorTotal() != null ?
               stats.getErrorTotal() : 0;
    }
    /**
     * 获取失败消息百分比
     * @param id 统计ID
     * @return 失败百分比，如 "10%"
     */
    public String getErrorPercentage(String id) {
        int successTotal = getSuccessTotal(id);
        int errorTotal = getErrorTotal(id);
        int totalMessages = successTotal + errorTotal;

        if (totalMessages == 0) {
            return "0%";
        }

        int percentage = Math.round((float) errorTotal / totalMessages * 100);
        return percentage + "%";
    }
}